package com.zxmzy.scaffold.core.loading

import android.app.Dialog
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.Window
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import androidx.annotation.StyleRes
import com.zxmzy.scaffold.core.R
import com.zxmzy.scaffold.core.databinding.DialogLoadingBinding
import com.zxmzy.scaffold.core.ext.layoutInflater

/**
 * @author zhangxiaoming
 * @date 2023/7/28
 * @description 加载中弹框
 */
class CenterLoadingDialog(
    context: Context,
    @StyleRes theme: Int = R.style.loading_dialog
) : Dialog(context, theme) {
    private var mBinding: DialogLoadingBinding
    private var animation: Animation? = null

    init {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        mBinding = DialogLoadingBinding.inflate(context.layoutInflater)
        setContentView(mBinding.root)
        setCanceledOnTouchOutside(false)
        setCancelable(false)
        window?.setBackgroundDrawable(ColorDrawable(0))
        initAnim()
    }

    private fun initAnim() {
        animation = RotateAnimation(
            0f, 360f,
            Animation.RELATIVE_TO_SELF, 0.5f,
            Animation.RELATIVE_TO_SELF, 0.5f
        ).apply {
            duration = 2000
            repeatCount = 40
            fillAfter = true
        }
    }

    override fun show() {
        super.show()
        mBinding.ivImage.startAnimation(animation)
    }

    override fun dismiss() {
        super.dismiss()
        mBinding.ivImage.clearAnimation()
    }

    override fun setTitle(title: CharSequence?) {
        if (!title.isNullOrEmpty()) {
            mBinding.tvMsg.text = title
        }
    }
}